package com.foreveross.proxyip.core.zk.task.strategy;

import java.lang.reflect.Constructor;
import java.util.List;

import org.apache.log4j.Logger;

import com.dayatang.domain.InstanceFactory;
import com.foreveross.proxyip.core.BaseCode;
import com.foreveross.proxyip.core.pools.AvailablePool;
import com.foreveross.proxyip.core.pools.thread.CheckInValidateThread;
import com.foreveross.proxyip.core.zk.ZkAppCenter;
import com.foreveross.proxyip.core.zk.task.ZkTask;
import com.foreveross.proxyip.exception.ProxyIpServiceException;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;
import com.foreveross.proxyip.util.ThreadUtils;

public class CheckInTask extends ZkTask {
	
	public final static String className = "PublicCheckInTask";
	
	protected static final Logger log =  Logger.getLogger(CheckInTask.class);
	@Override
	public boolean breakTask(String taskParams) throws Exception {
		AvailablePool pool = (AvailablePool)getPool(taskParams);
		if(pool.poolIpMap.size()>=pool.getProxyMax()){
			//池满为患
			return true;
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public int exec(Long[] taskNum, String taskParams) throws Exception {
		Long threadTimeout = Long.parseLong(BaseCode.getValue("THREAD_EXECUTE_TIMEOUT"));
		
		AvailablePool pool = this.getPool(taskParams);
		Constructor constructor = null;
		try {
			
			List iplist = null;
			if(taskNum==null||taskNum.length==0||taskNum[0]<=0L){
				return  -1;
			}
			IBaseRepository repository = InstanceFactory.getInstance(IBaseRepository.class,"channelEntityRepository");
				iplist = pool.getCheckInList(taskNum[0]);
				
				if(iplist==null||iplist.size()==0){
					return -1;
				}
		
			constructor = CheckInValidateThread.class.getConstructor(List.class,AvailablePool.class,IBaseRepository.class);
			log.debug(pool.poolSign+"~ start~~~~~~taskNum[0]:"+taskNum[0]+";iplist.size():"+iplist.size());
			ThreadUtils.openThreads(constructor, iplist, pool.threadMaxIpCount,threadTimeout,pool, repository);
			log.debug(pool.poolSign+"~ end~~~~~~iplist.size():"+pool.size());
		} catch (Exception e) {
			log.error(ProxyIpServiceException.getStackTrace(e));
		} 
		return 1;
	}
	
	
	
	
	public static String getSourceKey(AvailablePool pool){
		return pool.poolSign+"_source";
	}

}
